import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

//存放token的地方
export const TokenStore = defineStore('TokenStore', () => {
    const accessTokenPackage = ref(null)
    const accessToken = computed(() => {
        if (accessTokenPackage.value) {
            return accessTokenPackage.value
        }
        //从localStorage中获取token
        const localToken = window.localStorage.getItem("localAccessToken");
        if (localToken) {
            return localToken;
        }
        //如果没有token，则返回空null
        return null;
    })

    //设置token
    function saveAccessToken(data) {
        accessTokenPackage.value = data;
        window.localStorage.setItem("localAccessToken",data);
    }

    const refreshTokenPackage = ref(null)
    const refreshToken = computed(() => {
        if (refreshTokenPackage.value) {
            return refreshTokenPackage.value
        }
        const refreshToken = ref(null)
        //从localStorage中获取refreshToken
        const localRefreshToken = window.localStorage.getItem("localRefreshToken");
        if (localRefreshToken) {
            refreshToken.value = localRefreshToken;
        }
        return refreshToken.value
    })

    //设置refreshToken
    function saveRefreshToken(data) {
        refreshTokenPackage.value = data;
        window.localStorage.setItem("localRefreshToken", data);
    }
    return { accessToken, saveAccessToken, refreshToken, saveRefreshToken };
})

//存放userInfo的地方
export const UserStore = defineStore('UserStore', () => {
    const userPackage = ref(null);
    const userInfo = computed (() => {
        if (userPackage.value) {
            return userPackage.value
        }
        const localUser = window.localStorage.getItem("localUser");
        if (localUser) {
            const userJson = JSON.parse(localUser);
            userPackage.value = userJson;
            return userJson;
        }
        return null;
    })
    //设置user
    function saveUser(data) {
        userPackage.value = data;
        window.localStorage.setItem("localUser", JSON.stringify(data));
    }
    return { userInfo, saveUser };

})
